package com.gzw.dms.impl;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.gzw.dms.MyApplication;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.L;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by GaoZhiWei on 2015/12/31.
 */
public class MyLocationListener implements BDLocationListener {
    private BDLocation bdLocation = null;
    private String tag = "MyLocationListener---->";

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        this.bdLocation = bdLocation;
        StringBuffer sb = new StringBuffer(256);
//        sb.append("time : ");
//        sb.append(bdLocation.getTime());
        sb.append("\nerror code : ");
        sb.append(bdLocation.getLocType());
        sb.append("\nlatitude : ");
        sb.append(bdLocation.getLatitude());
        sb.append("\nlontitude : ");
        sb.append(bdLocation.getLongitude());
//        sb.append("\nradius : ");
//        sb.append(bdLocation.getRadius());
        if (bdLocation.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
//            sb.append("\nspeed : ");
//            sb.append(bdLocation.getSpeed());// 单位：公里每小时
//            sb.append("\nsatellite : ");
//            sb.append(bdLocation.getSatelliteNumber());
//            sb.append("\nheight : ");
//            sb.append(bdLocation.getAltitude());// 单位：米
//            sb.append("\ndirection : ");
//            sb.append(bdLocation.getDirection());// 单位度
            sb.append("\naddr : ");
            sb.append(bdLocation.getAddrStr());
            sb.append("\ndescribe : ");
            sb.append("gps定位成功");

        } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
            sb.append("\naddr : ");
            sb.append(bdLocation.getAddrStr());
//            //运营商信息
//            sb.append("\noperationers : ");
//            sb.append(bdLocation.getOperators());
//            sb.append("\ndescribe : ");
//            sb.append("网络定位成功");
//        } else if (bdLocation.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
//            sb.append("\ndescribe : ");
//            sb.append("离线定位成功，离线定位结果也是有效的");
//        } else if (bdLocation.getLocType() == BDLocation.TypeServerError) {
//            sb.append("\ndescribe : ");
//            sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
//        } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkException) {
//            sb.append("\ndescribe : ");
//            sb.append("网络不同导致定位失败，请检查网络是否通畅");
//        } else if (bdLocation.getLocType() == BDLocation.TypeCriteriaException) {
//            sb.append("\ndescribe : ");
//            sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
        }
//        sb.append("\nlocationdescribe : ");
//        sb.append(bdLocation.getLocationDescribe());// 位置语义化信息
//        List<Poi> list = bdLocation.getPoiList();// POI数据
//        if (list != null) {
//            sb.append("\npoilist size = : ");
//            sb.append(list.size());
//            for (Poi p : list) {
//                sb.append("\npoi= : ");
//                sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
//            }
//        }
//            L..i("BaiduLocationApiDem", sb.toString());
        L.i(tag + sb.toString());
        new Thread() {
            @Override
            public void run() {
                uploadGPS();
            }
        }.start();
    }

    @Override
    public void onConnectHotSpotMessage(String s, int i) {

    }

    private void uploadGPS() {
//        String i  = String.valueOf( bdLocation.getSpeed());
//        L.i(tag,i );
//
//        if (bdLocation.getSpeed()==0){
//
//        }else {

        L.i(tag, "uploadGPS()");
        if (!MyApplication.getIsUserLogin()) {
            L.i(tag, "未登录");
        } else {
            Map<String, String> map = new HashMap<>();
            MyApplication.setLat(String.valueOf(bdLocation.getLatitude()));
            MyApplication.setLng(String.valueOf(bdLocation.getLongitude()));
            if (String.valueOf(bdLocation.getLatitude()) == null || String.valueOf(bdLocation.getLatitude()).equals("")) {
                T.showShort(MyApplication.getmContext(), "请检测定位权限是否开启！");

            }
            map.put("lat", String.valueOf(bdLocation.getLatitude()));
            map.put("lng", String.valueOf(bdLocation.getLongitude()));
            map.put("carid", MyApplication.getUserInfo().getUsername());
            String json = JsonUtil.toJson(map);
//            String msg = HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("saveMapInfo"), "json=" + json);
            if (String.valueOf(bdLocation.getLatitude()).equals("4.9E-324")) {

            } else {
                String msg = HttpUtils.doPost("http://139.129.216.151:8090/scms/app.do?method=saveMapInfo&", "json=" + json);
//                String msg = HttpUtils.doPost("http://139.129.216.151:56788/scms/app.do?method=saveMapInfo&", "json=" + json);

                L.i(tag, msg);

            }
//        }
//            try {
//                Process process = Runtime.getRuntime().exec("logcat -d");
//                BufferedReader bufferedReader = new BufferedReader(
//                        new InputStreamReader(process.getInputStream()));
//
//                StringBuilder log=new StringBuilder();
//                String line;
//                while ((line = bufferedReader.readLine()) != null) {
//                    log.append(line);
//                }
//                String filePath = "/sdcard/Test/";
//                String fileName = "log.txt";
//
//                String lat = String.valueOf(log.toString());
//                writeTxtToFile(lat, filePath, fileName);
//            } catch (IOException e) {
//            }
//            String filePath = "/sdcard/Test/";
//            String fileName = "log.txt";
//
//            String lat = String.valueOf(bdLocation.getLatitude())+ " ; " +String.valueOf(bdLocation.getLongitude());
//            writeTxtToFile(lat, filePath, fileName);
        }
    }

    public void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }
}